'''
Created on Aug 17, 2012
@author: oabalbin
'''
import re
from collections import defaultdict

class Sample():
    def __init__(self,name,atributes, att_values):
        self.name=name
        self.mutations=[]
        self.annotation=defaultdict()
        for a, v in zip(atributes,att_values):
            self.annotation[a]=v
    def add_mutations(self,mutation_list):
        '''
        '''
        self.mutations=mutation_list[:]
        for mut in self.mutations:
            self.annotation[mut]="YES"
    
def samples_annotation(file):
    '''
    '''
    samples_list=defaultdict(Sample)
    ifile=open(file)    
    hd=[f.replace(' ','_') for f in ifile.next().strip('\n').split('\t')]
    
    for l in ifile:
        f=l.strip('\r\n').split('\t')
        samples_list[f[0]]=Sample(f[0],hd,f)
    return samples_list, hd
    
def read_mutation_file(file,samples_list):
    ifile=open(file)
    full_mutation_list=set()
    for l in ifile:
        f=l.strip('\r\n').split('\t')
        patient,pmutations=f[0],list(set(f[1:]))
        map(full_mutation_list.add,pmutations)
        if patient in samples_list:
            samples_list[patient].add_mutations(pmutations)
        else:
            print "patient no in list",patient
            
    return list(full_mutation_list) 

def create_header(samples_names,samples_list,infoheader,all_mutation_list):
    header=[]
    all_info=infoheader+all_mutation_list
    for info in  all_info:
        ol=[info]
        for j in range(len(samples_names)):
            sp=samples_names[j]
            if sp not in samples_list:
                #print "this sample is not in the annotation db",sp
                continue
            sample=samples_list[sp]
            if info in sample.annotation.keys():
                val=sample.annotation[info]
                if val=='':
                    val="NK"
                val=val.strip()
                val=val.replace(',','')
                #val.replace('.','')
                val=val.replace('(','')
                val=val.replace(')','')
                val=re.sub('/', '_', val)
                val=re.sub('\s+', '_', val)
                val=re.sub('-', '_', val)
                val=val.replace('._','_')
                val=val.replace('_.','_')
                val=val.replace('\'','')
                ol.append(val)
            else:
                ol.append("NK")
        header.append(ol)
    return header
    
def annotate_samples(annotation_file,mutations_file, samples_names):
    '''
    '''
    #annotfile='/exds/users/oabalbin/projects/lungseq/MINE_results_v0.2.0/Lung_RNASeq_Cohort_Sample_Clinical_Information.csv'
    #muations_file='/exds/users/oabalbin/projects/lungseq/MINE_results_v0.2.0/summary_SNV_LUNG.txt'
    samples_list,infoheader = samples_annotation(annotation_file)
    all_mutation_list=read_mutation_file(mutations_file,samples_list)
    matrix_header=create_header(samples_names,samples_list,infoheader,all_mutation_list)
    return matrix_header


'''
annotfile='/exds/users/oabalbin/projects/lungseq/MINE_results_v0.2.0/Lung_RNASeq_Cohort_Sample_Clinical_Information.csv'
muations_file='/exds/users/oabalbin/projects/lungseq/MINE_results_v0.2.0/summary_SNV_LUNG.txt'
samples='/exds/users/oabalbin/projects/lungseq/MINE_results_v0.2.0/samples_header.txt'
samples_names=defaultdict()

for i,sp in enumerate(open(samples).next().strip('\n').split('\t')):
    samples_names[i]=sp
header=annotate_samples(annotfile,muations_file,samples_names)
of=open('/exds/users/oabalbin/projects/lungseq/MINE_results_v0.2.0/header_test.txt','w')
for h in header:
    print len(h),h
    of.write(",".join(h).replace(',','\t')+'\n')
'''